Exploring Numeric Data Types: int, float, and complex
Course: Python Training Course
Topic: Exploring Numeric Data Types: int, float, and complex
Course Link: Python Training Course at JustAcademy
Demo Link: Register for a Course Demo
Website: Visit JustAcademy
1. Introduction to Numeric Data Types in Python
Numeric data types are used to represent and perform calculations with numbers. They are essential in almost every programming application, including financial calculations, scientific computing, data analysis, game development, automation, and mathematical modeling.
Python provides three primary built-in numeric data types: int, float, and complex. Each type is designed to represent a different kind of numerical value.
- int: Represents whole numbers without a fractional component.
- float: Represents floating-point numbers, which can contain fractional parts or use scientific notation.
- complex: Represents complex numbers containing real and imaginary components.
Python determines the numeric type from the value assigned to a variable. You can use the built-in type() function to identify the type of a value.
Example: Identifying Numeric Data Types
age = 25
price = 149.99
complex_number = 3 + 4j
print(type(age))
print(type(price))
print(type(complex_number))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
Explanation: The value 25 is an integer, 149.99 is a floating-point number, and 3 + 4j is a complex number.
2. Learning Objectives
After studying this topic, learners should be able to:
- Understand Python's three primary numeric data types.
- Create and use integer, floating-point, and complex values.
- Identify numeric types using
type().
- Convert values between numeric types using
int(), float(), and complex().
- Perform arithmetic operations on numeric values.
- Understand integer division, floating-point precision, and complex arithmetic.
- Recognize common numeric conversion errors.
- Apply numeric data types in practical Python programs.
3. Understanding the int Data Type
The int data type represents integers, which are whole numbers without a fractional part. Integers can be positive, negative, or zero.
3.1 Examples of Integers
student_count = 45
temperature = -8
balance_change = 0
population = 1500000
print(student_count)
print(temperature)
print(balance_change)
print(population)
In this example, all four variables contain integer values.
3.2 Characteristics of int
- Integers do not contain a decimal point.
- They can represent positive numbers, negative numbers, and zero.
- Python integers support arbitrary precision, subject to available memory.
- They are commonly used for counting, indexing, quantities, and whole-number calculations.
- Integer values can participate in arithmetic operations with other numeric types.
3.3 Large Integer Values
Python supports integers larger than the fixed-width integer ranges commonly used in some other programming languages. The practical limit is primarily determined by available memory.
large_number = 987654321987654321987654321
print(large_number)
print(type(large_number))
Output:
987654321987654321987654321
<class 'int'>
This feature makes Python useful for calculations involving very large whole numbers.
3.4 Integer Literals in Different Number Systems
Python supports integer literals in decimal, binary, octal, and hexadecimal formats.
| Number System |
Prefix |
Example |
Decimal Value |
| Decimal |
None |
25 |
25 |
| Binary |
0b or 0B |
0b11001 |
25 |
| Octal |
0o or 0O |
0o31 |
25 |
| Hexadecimal |
0x or 0X |
0x19 |
25 |
Example:
decimal_number = 25
binary_number = 0b11001
octal_number = 0o31
hexadecimal_number = 0x19
print(decimal_number)
print(binary_number)
print(octal_number)
print(hexadecimal_number)
Output:
25
25
25
25
Although the literals use different number systems, Python evaluates each of them to the same integer value.
3.5 Integer Arithmetic
Python supports several arithmetic operations on integers.
a = 20
b = 6
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a // b) # Floor division
print(a % b) # Remainder
print(a ** b) # Exponentiation
Output:
26
14
120
3
2
64000000
The // operator performs floor division, while % returns the remainder. For integer operands, floor division produces an integer result.
4. Understanding the float Data Type
The float data type represents floating-point numbers. These numbers can include fractional parts and can also be expressed using scientific notation.
Floating-point values are useful when working with measurements, prices, percentages, averages, distances, and other calculations that require fractional values.
4.1 Examples of Floating-Point Values
product_price = 249.99
height = 5.8
temperature = -2.5
interest_rate = 7.25
whole_number_as_float = 10.0
print(product_price)
print(height)
print(temperature)
print(interest_rate)
print(whole_number_as_float)
All five variables contain floating-point values, including 10.0, which has no fractional component but is still a float.
4.2 Characteristics of float
- Floating-point literals usually contain a decimal point or an exponent.
- They can represent positive and negative fractional values.
- They support arithmetic operations such as addition, subtraction, multiplication, and division.
- They have finite precision, so some decimal fractions cannot be represented exactly in binary floating-point format.
- They are useful for scientific calculations and approximate real-number calculations.
4.3 Scientific Notation
Python allows floating-point values to be written in scientific notation using the letter e or E. The exponent indicates a power of ten.
distance = 3.5e3
small_value = 4.2e-3
large_value = 6.0E6
print(distance)
print(small_value)
print(large_value)
Output:
3500.0
0.0042
6000000.0
For example, 3.5e3 means \(3.5 \times 10^3\), which equals 3500.0.
4.4 Floating-Point Arithmetic
price = 199.99
tax = 18.0
tax_amount = price * tax / 100
final_price = price + tax_amount
print("Price:", price)
print("Tax:", tax_amount)
print("Final price:", final_price)
This program calculates a tax amount and adds it to the original price. It demonstrates how floating-point values can be used in everyday calculations.
4.5 Floating-Point Precision
Computers store floating-point numbers using a finite binary representation. Some decimal fractions, such as 0.1, cannot be represented exactly in that format. As a result, certain calculations may produce small rounding differences.
result = 0.1 + 0.2
print(result)
print(result == 0.3)
A typical output is:
0.30000000000000004
False
This does not mean that Python's addition is broken. It reflects the finite precision of binary floating-point arithmetic.
4.6 Comparing Floating-Point Numbers Safely
For approximate calculations, compare the difference between two values against a tolerance instead of relying on exact equality.
result = 0.1 + 0.2
expected = 0.3
tolerance = 1e-9
if abs(result - expected) < tolerance:
print("Values are approximately equal")
else:
print("Values are different")
Python also provides the math.isclose() function for approximate comparisons.
import math
print(math.isclose(0.1 + 0.2, 0.3))
For financial calculations that require exact decimal arithmetic, consider the decimal.Decimal type rather than ordinary binary floats.
5. Understanding the complex Data Type
The complex data type represents complex numbers. A complex number consists of a real component and an imaginary component. Complex numbers are used in mathematics, electrical engineering, signal processing, physics, and specialized scientific computing.
A complex number is commonly written in the form:
z = a + bj
a is the real component.
b is the imaginary component's coefficient.
j represents the imaginary unit in Python's notation, where \(j^2 = -1\).
Python uses j or J to identify the imaginary component.
5.1 Creating Complex Numbers
z1 = 3 + 4j
z2 = 5 - 2j
z3 = 7j
z4 = complex(6, 3)
print(z1)
print(z2)
print(z3)
print(z4)
Output:
(3+4j)
(5-2j)
7j
(6+3j)
The expression complex(6, 3) creates a complex number with real part 6 and imaginary part 3.
5.2 Accessing Real and Imaginary Components
Python provides the .real and .imag attributes to retrieve the two components of a complex number.
z = 8 + 5j
print("Real part:", z.real)
print("Imaginary part:", z.imag)
print("Type:", type(z))
Output:
Real part: 8.0
Imaginary part: 5.0
Type: <class 'complex'>
The real and imaginary components of a Python complex number are returned as floating-point values.
5.3 Complex Number Arithmetic
Python supports addition, subtraction, multiplication, and division for complex numbers.
z1 = 3 + 2j
z2 = 1 + 4j
print("Addition:", z1 + z2)
print("Subtraction:", z1 - z2)
print("Multiplication:", z1 * z2)
print("Division:", z1 / z2)
Output:
Addition: (4+6j)
Subtraction: (2-2j)
Multiplication: (-5+14j)
Division: (0.5294117647058824-0.6470588235294118j)
Explanation:
- Addition: Add the real components and the imaginary components separately.
- Subtraction: Subtract the corresponding components.
- Multiplication: Expand the expression and use \(j^2 = -1\).
- Division: Python calculates the quotient using complex arithmetic.
5.4 Magnitude of a Complex Number
The magnitude, or modulus, of a complex number is the distance from the origin in the complex plane. Python's abs() function calculates this value.
z = 3 + 4j
print(abs(z))
Output:
5.0
The magnitude is calculated mathematically as:
\(|z| = \sqrt{a^2 + b^2}\)
For 3 + 4j, the magnitude is \(\sqrt{3^2 + 4^2} = 5\).
5.5 Complex Conjugates
The complex conjugate keeps the real component unchanged and reverses the sign of the imaginary component.
z = 3 + 4j
print(z.conjugate())
Output:
(3-4j)
Complex conjugates are useful in mathematical operations involving complex division, signal processing, and engineering calculations.
5.6 Limitations of Complex Numbers
Complex numbers support many arithmetic operations, but they do not support ordinary ordering comparisons such as <, >, <=, or >=.
z = 3 + 4j
print(z == 3 + 4j) # Valid equality comparison
# print(z > 2) # TypeError: complex numbers are not ordered
Equality comparisons are supported, but complex values cannot be ordered in the same way as real numbers. If you need to compare their magnitudes, use abs().
6. Comparison of int, float, and complex
| Feature |
int |
float |
complex |
| Represents |
Whole numbers |
Floating-point numbers |
Real and imaginary components |
| Example |
25 |
25.75 |
3 + 4j |
| Decimal point required |
No |
Usually yes, or exponent notation |
No; imaginary notation uses j |
| Fractional values |
Not represented directly |
Supported approximately |
Supported through real and imaginary components |
| Precision |
Arbitrary precision subject to memory |
Finite binary floating-point precision |
Real and imaginary parts use floating-point values |
| Ordering comparisons |
Supported |
Supported |
Not supported |
| Common uses |
Counts, indexes, quantities |
Measurements, averages, scientific calculations |
Electrical engineering, mathematics, signal processing |
| Conversion function |
int() |
float() |
complex() |
7. Checking Numeric Types with type() and isinstance()
The type() function identifies the exact type of an object. The isinstance() function checks whether an object belongs to a specified type or compatible class hierarchy.
7.1 Using type()
number1 = 100
number2 = 100.5
number3 = 2 + 3j
print(type(number1))
print(type(number2))
print(type(number3))
7.2 Using isinstance()
age = 25
price = 99.99
z = 2 + 3j
print(isinstance(age, int))
print(isinstance(price, float))
print(isinstance(z, complex))
Output:
True
True
True
Important note: In Python, bool is a subclass of int. Therefore, isinstance(True, int) returns True. If an application must distinguish Boolean values from integers, use type(value) is int when appropriate.
8. Converting Between Numeric Data Types
Python provides built-in functions for converting values to specific numeric types. These conversions are often called type casting.
8.1 Converting to int
The int() function converts supported values to integers. When converting a float, it truncates the fractional part toward zero rather than rounding to the nearest integer.
print(int(12.9))
print(int(12.1))
print(int(-12.9))
print(int("250"))
Output:
12
12
-12
250
Important: int(12.9) returns 12, not 13. For rounding, use round(); for rounding down or up, consider math.floor() or math.ceil().
8.2 Converting to float
The float() function converts supported integers, numeric strings, and other compatible values to floating-point numbers.
print(float(10))
print(float("25.75"))
print(float("-8.5"))
Output:
10.0
25.75
-8.5
8.3 Converting to complex
The complex() function creates a complex number. It accepts a real value and an optional imaginary value.
print(complex(5))
print(complex(5, 2))
print(complex(0, 7))
Output:
(5+0j)
(5+2j)
7j
8.4 Type Conversion Table
| Expression |
Result |
Explanation |
int(8.9) |
8 |
Fractional part is truncated. |
float(8) |
8.0 |
Integer becomes a float. |
complex(8) |
(8+0j) |
Creates a complex number with zero imaginary part. |
complex(8, 3) |
(8+3j) |
Creates a complex number with both components. |
int("45") |
45 |
Converts a valid integer string. |
float("4.75") |
4.75 |
Converts a valid numeric string. |
8.5 Invalid Conversions
Conversions fail when the input cannot be interpreted as the requested numeric type.
# This raises ValueError:
# int("hello")
# This raises ValueError:
# float("ten")
# This raises TypeError:
# int(3 + 4j)
Python does not directly convert a complex number to an integer or float because doing so would discard information. If the real component is specifically required, access it explicitly, such as int((3 + 4j).real).
9. Arithmetic Operations and Mixed Numeric Types
Python supports arithmetic operations between compatible numeric types. When numeric operands have different types, Python often converts the result to a type capable of representing the operation.
integer_value = 10
float_value = 2.5
complex_value = 1 + 2j
result1 = integer_value + float_value
result2 = integer_value + complex_value
result3 = float_value + complex_value
print(result1, type(result1))
print(result2, type(result2))
print(result3, type(result3))
Output:
12.5 <class 'float'>
(11+2j) <class 'complex'>
(3.5+2j) <class 'complex'>
In general, arithmetic involving an integer and a float produces a float, while arithmetic involving a complex number and a real numeric value produces a complex result.
9.1 Division Operators
Python provides several division-related operators, each with a different purpose.
| Operator |
Example |
Result |
Purpose |
/ |
10 / 4 |
2.5 |
True division. |
// |
10 // 4 |
2 |
Floor division. |
% |
10 % 4 |
2 |
Remainder. |
** |
2 ** 3 |
8 |
Exponentiation. |
Floor division rounds the quotient down toward negative infinity. For example, -7 // 2 produces -4, not -3.
9.2 Operations Not Supported by Complex Numbers
Complex numbers do not support every operation available to integers and floats. In particular, floor division, modulo, and ordering comparisons are not defined for complex values.
z = 2 + 3j
print(z + 1)
print(z * 2)
print(abs(z))
# The following operations are invalid:
# z // 2
# z % 2
# z > 1
10. Useful Built-in Functions for Numeric Values
| Function |
Purpose |
Example |
type() |
Identifies an object's type. |
type(10.5) |
int() |
Converts a supported value to an integer. |
int(8.7) |
float() |
Converts a supported value to a float. |
float(8) |
complex() |
Creates a complex number. |
complex(2, 3) |
abs() |
Returns absolute value or complex magnitude. |
abs(-15) |
round() |
Rounds a real number according to Python's rounding rules. |
round(3.14159, 2) |
pow() |
Calculates a power. |
pow(2, 4) |
divmod() |
Returns quotient and remainder as a pair. |
divmod(17, 5) |
math.sqrt() |
Calculates the square root of a suitable real value. |
math.sqrt(25) |
cmath.sqrt() |
Calculates a complex square root. |
cmath.sqrt(-1) |
Example Using Numeric Functions
import math
import cmath
print(abs(-25))
print(round(3.14159, 2))
print(pow(2, 5))
print(divmod(17, 5))
print(math.sqrt(25))
print(cmath.sqrt(-1))
Output:
25
3.14
32
(3, 2)
5.0
1j
11. Working with User Input and Numeric Types
The input() function returns user input as a string. To perform calculations, convert the input to an appropriate numeric type.
11.1 Reading Integer Input
age = int(input("Enter your age: "))
print("Next year, you will be", age + 1)
11.2 Reading Floating-Point Input
price = float(input("Enter the product price: "))
quantity = int(input("Enter the quantity: "))
total = price * quantity
print("Total price:", total)
11.3 Handling Invalid Numeric Input
If a user enters text that cannot be converted to the required numeric type, Python raises a ValueError. Use exception handling to respond to invalid input gracefully.
try:
number = float(input("Enter a number: "))
print("Double:", number * 2)
except ValueError:
print("Invalid input. Please enter a valid number.")
This approach prevents the program from terminating unexpectedly when the user enters an invalid number.
12. Numeric Data Types in Real-World Applications
| Application |
Recommended Type |
Example |
| Counting students |
int |
student_count = 120 |
| Tracking product quantity |
int |
quantity = 5 |
| Measuring temperature |
float |
temperature = 36.6 |
| Calculating average marks |
float |
average = 82.5 |
| Scientific measurements |
float or specialized numeric types |
distance = 1.5e8 |
| Electrical signal analysis |
complex |
signal = 3 + 2j |
| Engineering calculations |
complex where appropriate |
impedance = 4 + 3j |
Practical consideration: For monetary values that require exact decimal arithmetic, use decimal.Decimal and apply appropriate rounding rules. Ordinary floats can introduce small binary representation differences.
13. Practical Project: Student Marks Calculator
Objective: Create a program that accepts student marks, calculates the total and average, and displays the result using integer and floating-point data types.
# Student Marks Calculator
student_name = input("Enter student name: ")
mark1 = float(input("Enter marks for Subject 1: "))
mark2 = float(input("Enter marks for Subject 2: "))
mark3 = float(input("Enter marks for Subject 3: "))
total = mark1 + mark2 + mark3
average = total / 3
print("\n--- STUDENT RESULT ---")
print("Student:", student_name)
print("Total Marks:", total)
print("Average Marks:", round(average, 2))
if average >= 75:
print("Grade: Distinction")
elif average >= 40:
print("Grade: Pass")
else:
print("Grade: Fail")
Project Explanation
- The program reads the student's name as a string.
- It converts each mark to a float to allow decimal marks.
- It calculates the total using addition.
- It divides the total by three to calculate the average.
- It rounds the displayed average to two decimal places.
- It uses conditional statements to assign a grade.
Extension task: Add input validation to ensure that marks fall within the range 0 to 100. Calculate the percentage and display the highest and lowest marks.
14. Practical Project: Complex Number Calculator
Objective: Practice creating and manipulating complex numbers using Python.
# Complex Number Calculator
z1 = complex(3, 4)
z2 = complex(2, -1)
print("First number:", z1)
print("Second number:", z2)
print("Addition:", z1 + z2)
print("Subtraction:", z1 - z2)
print("Multiplication:", z1 * z2)
print("Division:", z1 / z2)
print("Magnitude of first number:", abs(z1))
print("Real component:", z1.real)
print("Imaginary component:", z1.imag)
print("Conjugate:", z1.conjugate())
This project demonstrates complex-number creation, arithmetic, component access, magnitude calculation, and conjugation.
15. Common Mistakes and Troubleshooting
| Mistake |
Example |
Explanation and Solution |
| Assuming input is numeric |
age = input("Age: ") |
input() returns a string. Convert it using int() or another suitable function. |
| Expecting int() to round |
int(7.9) |
The result is 7 because the fractional part is truncated. Use round() if rounding is required. |
| Comparing floats for exact equality |
0.1 + 0.2 == 0.3 |
Binary floating-point representation may introduce a small difference. Use math.isclose() for approximate comparisons. |
| Converting arbitrary text |
int("hello") |
Raises ValueError. Validate input or use exception handling. |
| Converting complex values directly |
float(2 + 3j) |
Raises TypeError. Use the real or imaginary component if that is what the calculation requires. |
| Using ordering comparisons with complex values |
(2 + 3j) > 1 |
Raises TypeError. Compare magnitudes using abs() if appropriate. |
| Assuming all numeric division returns int |
10 / 2 |
True division returns a float: 5.0. |
| Using float for every monetary calculation |
total = 0.1 + 0.2 |
For exact decimal arithmetic, consider decimal.Decimal. |
16. Hands-On Practice Exercises
Exercise 1: Identify Numeric Types
Create variables containing 100, 100.75, and 5 + 7j. Display each value and its type.
Exercise 2: Integer Operations
Write a program that accepts two integers and displays their sum, difference, product, quotient, floor quotient, and remainder.
Exercise 3: Float Conversion
Convert the string "125.50" into a floating-point number. Multiply it by three and display the result.
Exercise 4: Complex Number Components
Create a complex number 6 + 8j. Display its real component, imaginary component, magnitude, and conjugate.
Exercise 5: Type Conversion
Test the results of int(9.8), float(9), and complex(9, 2). Explain how the type and value change.
Exercise 6: Floating-Point Precision
Calculate 0.1 + 0.2, compare it with 0.3, and repeat the comparison using math.isclose().
Exercise 7: Shopping Bill
Create a program that accepts a product price as a float and quantity as an integer. Calculate the subtotal and display the result.
Exercise 8: Complex Arithmetic
Create two complex numbers and calculate their sum, difference, product, quotient, and individual magnitudes.
17. Interview Questions and Answers
Q1. What are the three main numeric data types in Python?
Answer: The three primary numeric data types are int for integers, float for floating-point numbers, and complex for complex numbers.
Q2. What is an integer in Python?
Answer: An integer is a whole number without a fractional part. Python integers support arbitrary precision, subject to available memory.
Q3. What is a float?
Answer: A float represents a floating-point number. It can contain a fractional part or use scientific notation, and it has finite precision.
Q4. What is a complex number?
Answer: A complex number contains a real component and an imaginary component. Python uses j to represent the imaginary unit, as in 3 + 4j.
Q5. How can you identify a variable's data type?
Answer: Use the type() function to retrieve the exact type of a value. The isinstance() function can check whether a value belongs to a type or compatible class hierarchy.
Q6. What is the difference between int and float?
Answer: An int represents whole numbers, while a float represents floating-point values that may include fractional components.
Q7. What does int(7.9) return?
Answer: It returns 7. Conversion from a float to an integer truncates the fractional part toward zero; it does not round to the nearest integer.
Q8. Why does 0.1 + 0.2 sometimes produce 0.30000000000000004?
Answer: Many decimal fractions cannot be represented exactly in binary floating-point format. Small representation differences can appear in arithmetic results.
Q9. How do you access the real and imaginary components of a complex number?
Answer: Use the .real and .imag attributes, such as (3 + 4j).real and (3 + 4j).imag.
Q10. Can complex numbers be compared using greater-than or less-than operators?
Answer: No. Python does not define ordinary ordering comparisons for complex numbers. Use abs() to compare magnitudes if that matches the intended calculation.
Q11. What happens when an integer is added to a float?
Answer: Python performs mixed numeric arithmetic and generally returns a float for addition between an integer and a float.
Q12. What is the purpose of complex()?
Answer: The complex() function creates a complex number from a real component and an optional imaginary component.
Q13. How can invalid numeric input be handled?
Answer: Use a try and except ValueError block when converting user input to numeric values.
Q14. Why might Decimal be preferable to float for money?
Answer: decimal.Decimal supports decimal arithmetic with configurable precision and rounding, making it useful for many financial calculations where binary floating-point representation is undesirable.
18. Quick Revision Checklist
int represents whole numbers.
float represents floating-point numbers.
complex represents numbers with real and imaginary components.
- Use
type() to identify an object's exact type.
- Use
int(), float(), and complex() for supported conversions.
- Remember that
int() truncates fractional values rather than rounding them.
- Use
j or J to write imaginary components.
- Access complex components through
.real and .imag.
- Use
abs() to calculate the magnitude of a complex number.
- Understand that floats have finite precision.
- Use
math.isclose() for suitable approximate comparisons.
- Handle invalid conversions with exception handling.
- Consider
decimal.Decimal for financial calculations requiring decimal arithmetic.
19. Conclusion
Understanding Python's numeric data types is an important foundation for writing effective programs. The int type is suitable for whole-number values, float is useful for fractional and scientific calculations, and complex supports mathematical operations involving real and imaginary components.
Learning how to create numeric values, inspect their types, convert between types, perform arithmetic, and handle precision limitations helps prevent common programming errors. These concepts are useful in everyday scripting as well as advanced applications in data analysis, automation, engineering, and scientific computing.
Continue learning with the Python Training Course at JustAcademy. You can register for a course demo to explore the learning options, or visit the JustAcademy website for additional information.